package com.lsk.api;

import com.jfinal.kit.HttpKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.lsk.mobile.MobileServices;
import com.lsk.util.*;

import java.text.DecimalFormat;
import java.util.*;

/**
 * 易缴费接口
 */
public class YJFService {

    static String appId = "17280184950";

    static String appSert = "6c2b8815b58d42cb8247a4a5a343d07a";

    static String cardSubmitUrl = "http://api.douleka.com.cn:11140/api/singleSupply";


    static String cardQueryUrl = "http://api.douleka.com.cn:11140/supply/apiQuerySupplyCard";

    /**
     * 卡片提交
     */
    public static void   cardSubmit(Record temp) {

        //Cache cache = Redis.use();



        try {

            String cardId = temp.getStr("id");

            Map<String, String> parameters = new HashMap<>();

            parameters.put("account", appId);

            String orderId = "YJF" + DateUtil.getSdfTimes() + Tools.getRandomNum();

            parameters.put("orderId", orderId);

            String inputCardNumber = temp.getStr("cardNumber");

            parameters.put("cardNumber", inputCardNumber);

            String inputCardPassword = temp.getStr("cardPassword");

            parameters.put("cardPwd", inputCardPassword);

            String face = temp.getStr("feedbackValue");

            face=new DecimalFormat("######0").format(Double.valueOf(face));

            parameters.put("uploadFace", face);//面值

            String feedbackId = temp.getStr("feedbackId");

            Record saleCardDiscount = Db.findFirst("select * from commodity_facevalue where id=?", feedbackId);
            parameters.put("userPrice", saleCardDiscount.getStr("saleCardDiscount"));

            String confiSql = "SELECT `value` from sys_config where element='domain'";

            String domain = Db.queryStr(confiSql);

            parameters.put("callBackAddress", "http://" + domain.replace("http://", "")
                    + "/mobile/yjfCallback");

            parameters.put("area", "0");

            Map<String, String> signMap = new HashMap<>();

            signMap = parameters;

            String sign = submitSign(signMap);

            parameters.put("sign", sign);//加密签名，加密原文请参考下面的加密拼接，MD5加密

            Syslog.info("向易缴费推送参数为：" + JsonUtil.getJsonStr(parameters));

            System.out.println(JsonUtil.getJsonStr(parameters));

            String result = HttpKit.get(cardSubmitUrl, parameters);

            System.out.println(result);

            Map<String, Object> resultMap = JsonUtil.getMapFromJsonObjStr(result);


            Syslog.info("易缴费推送结果为：" + JsonUtil.getJsonStr(result));


            temp.remove("code").set("createTime", new Date()).set("returnJson", result)
                    .remove("id").set("cardId", cardId).set("id", orderId);

            Record myData = new Record().set("id", orderId).set("cardId", cardId).set("classId", temp.getStr("classId")
            ).set("commodityId", temp.getStr("commodityId")).set("commodityName", temp.getStr("commodityName"))
                    .set("feedbackId", temp.getStr("feedbackId")).set("feedbackValue", temp.getStr("feedbackValue"))
                    .set("discount", saleCardDiscount.getStr("saleCardDiscount")).set("createTime", new Date()).set("returnCode", resultMap.get("status")
                    ).set("returnMsg", ApiReturn.getMsgByCode(resultMap.get("status") + "", "0"))
                    .set("returnJson", result).set("cardNumber", temp.getStr("cardNumber")).set("cardPassword", temp.getStr("cardPassword"))
                    .set("orderId", temp.getStr("orderId")).set("memberId", temp.getStr("memberId")).set("imgPath", temp.getStr("imgPath"))
                    .set("className", temp.getStr("className"));
            Db.save("card_send_logs", "id", myData);
            //Db.save("card_send_logs", "id", temp);

            String status = resultMap.get("status") + "";

            if ("0".equals(status)) {//提交成功

                Record card = new Record().set("id", cardId).set("state", 2).set("msg", ApiReturn.getMsgByCode(status, "0")+"(易缴费)");

                Db.update("card", "id", card);




            }else if("18006".equals(status)){  //供货价格错误.设置为处理中

                Record card = new Record().set("id", cardId).set("state", 2).set("msg",ApiReturn.getMsgByCode(status,"0"));

                Db.update("card", "id", card);
            }else if("23007".equals(status)){
                Record card = new Record().set("id", cardId).set("state",6).set("msg",ApiReturn.getMsgByCode(status,"0"));

                Db.update("card", "id", card);

            }else{  //提交失败
                Record card = new Record().set("id", cardId).set("state", 3).set("msg",ApiReturn.getMsgByCode(status,"0"));

                Db.update("card", "id", card);
            }



        } catch (Exception e) {

            Syslog.error("推送到易缴费平台异常，卡信息：" + temp.toJson());

            Syslog.error(e);

        }


    }


    /**
     * 提前卡签名
     *
     * @param parameters
     * @return
     */
    public static String submitSign(Map<String, String> parameters) {

        String orderId = parameters.get("orderId");

        String sign = "account" + appId + "orderId" + orderId + "cardNumber" + parameters.get("cardNumber")
                + "cardPwd" + parameters.get("cardPwd") + "uploadFace" + parameters.get("uploadFace")
                + "userPrice" + parameters.get("userPrice") + "area" + parameters.get("area") + appSert;

        System.out.println(UtilUrlEncode.URLDecoderString(sign));

        sign = MD5.md5(UtilUrlEncode.URLDecoderString(sign));

        return sign;

    }

    /**
     * 查询卡签名
     *
     * @param parameters
     * @return
     */
    public static String querySign(Map<String, String> parameters) {


        String sign = "userAccount" + parameters.get("userAccount")
                + "orderId" + parameters.get("orderId") + "key" + appSert;

        System.out.println(UtilUrlEncode.URLDecoderString(sign));

        sign = MD5.md5(UtilUrlEncode.URLDecoderString(sign));

        return sign;

    }


    public static void main(String[] strings) {

        YJFService yjfService = new YJFService();

        List<Record> cardList = new ArrayList<>();

        Record record = new Record();

        record.set("feedbackValue", 30).set("discount", 0.98).set("cardNumber", "18758011746154525")
                .set("cardPassword", "433470132627164269");

        cardList.add(record);


    }

    /**
     * 验证签名
     *
     * @param theirSign
     * @param theirData
     * @return
     * @throws Exception
     */
    public boolean checkSign(String theirSign, String theirData) throws Exception {
        String newSign = MD5.md5(UtilUrlEncode.URLDecoderString(theirData));
        if (theirSign.equals(newSign) && theirSign == newSign) {
            return true;
        }
        return false;
    }


    /**
     * 查询卡状态
     */
    public static void queryCardState() {

        try {


            Map<String, String> parameters = new HashMap<>();

            parameters.put("userAccount", appId);


            List<Record> unSaleCards = Db.find("select * from card where state = '1' or state = '1' or state='2'  limit 0,10");

            for (int i = 0; i < unSaleCards.size(); i++) {

                try {

                    String cardSendId = Db.queryStr("select id from card_send_logs where cardId='" + unSaleCards.get(i).getStr("id") + "'");

                    if (cardSendId.contains("YJF")) {//易缴费卡

                        parameters.put("orderId", cardSendId);

                        String sign = querySign(parameters);

                        parameters.put("sign", sign);//加密签名，加密原文请参考下面的加密拼接，MD5加密

                        System.out.println(JsonUtil.getJsonStr(parameters));

                        String result = HttpKit.get(cardQueryUrl, parameters);

                        Syslog.info("易缴费平台查询卡状态返回结果为：" + result);

                        Map<String, Object> resultMap = JsonUtil.getMapFromJsonObjStr(result);

                        /**
                         * status	int	查询状态
                         * orderId	string	订单号
                         * orderStatus	int
                         * judgeFace	string	预判面值
                         * failReason	string	失败原因
                         * settlePrice	string	结算金额
                         */


                        String orderStatus = ((Map<String, String>) resultMap.get("order")).get("orderStatus");//订单状态 订单状态 0处理中 1 销卡成功 2销卡失败

                        /*更新卡信息*/
                        //boolean flag = updateCardState(orderStatus, cardSendId);
                        //Syslog.info("上送记录id为" + cardSendId + "数据存储结果为:" + flag);

                    }
                } catch (Exception e) {
                    Syslog.error(e);
                }

            }
        } catch (Exception e) {

            e.printStackTrace();

            Syslog.error(e);

        }


    }

    /**
     * 更新order状态
     *
     * @param orderStatus
     * @param cardSendLogId
     * @return
     */
    private static boolean updateCardState(String orderStatus, String cardSendLogId) {
        boolean flag = false;
        MobileServices mobileServices = new MobileServices();
        switch (orderStatus) {
            case "0":       //处理中
                return false;
            case "1":       //销卡成功
                flag = mobileServices.updateCardState(cardSendLogId, true);
                break;
            case "2":       //销卡失败
                flag = mobileServices.updateCardState(cardSendLogId, false);
                break;
            default:
                return false;
        }
        return flag;
    }


}
